#include "util_timer.h"

static void default_timer_thread(union sigval v)
{
    timer_conf_t *conf = (timer_conf_t *)v.sival_ptr;
    conf->cnt_cur++;
    if (conf->cnt_max == conf->cnt_cur)
    {
         timer_stop(conf);
    }
    
    //调用户回调函数
    conf->func(conf->arg);
}

int timer_start(timer_conf_t *conf, int interval, int repeat, handler_t func,void *arg)
{
    if (conf == NULL || interval <= 0)
    {
        return -1;
    }
    memset(conf, 0x00, sizeof(timer_conf_t));

    // 定时器到期事件设置
    conf->evp.sigev_value.sival_ptr = conf;
    conf->evp.sigev_notify = SIGEV_THREAD;
    conf->evp.sigev_notify_function = default_timer_thread;
    conf->func = func;
    conf->arg = arg;
    if (timer_create(CLOCK_REALTIME, &conf->evp, &conf->timer) == -1)
    {
        perror("fail to timer_create");
        return -1;
    }

    //周期性
    if (repeat >= 0)
    {
        conf->cnt_max = (repeat == 0) ? 1 : repeat;
    }
    else
    {
        conf->cnt_max = -1;
    }

    //定时器间隔设置
    //周期性间隔
    conf->it.it_interval.tv_sec = interval / 1000;
    conf->it.it_interval.tv_nsec = (interval % 1000) * 1000000;
    //首次设置后超时时间
    conf->it.it_value.tv_sec = interval / 1000;
    conf->it.it_value.tv_nsec = (interval % 1000) * 1000000;
    if (timer_settime(conf->timer, 0, &conf->it, NULL) == -1)
    {
        perror("fail to timer_settime");
        return -1;
    }

    return 0;
}

int timer_config(timer_conf_t *conf,int timeout)
{
     //周期性间隔
    conf->it.it_interval.tv_sec = timeout / 1000;
    conf->it.it_interval.tv_nsec = (timeout % 1000) * 1000000;
    //首次设置后超时时间
    conf->it.it_value.tv_sec = timeout / 1000;
    conf->it.it_value.tv_nsec = (timeout % 1000) * 1000000;
    return timer_settime(conf->timer, 0, &conf->it, NULL);
}

int timer_stop(timer_conf_t *conf)
{
    conf->it.it_interval.tv_sec = 0;
    conf->it.it_interval.tv_nsec = 0;
    conf->it.it_value.tv_sec = 0;
    conf->it.it_value.tv_nsec = 0;
    return timer_settime(conf->timer, 0, &conf->it, NULL);
}

int timer_destory(timer_conf_t *conf)
{
    return timer_delete(conf->timer);
}

#if 0
#include <sys/reboot.h>
void timer_thread(void *arg)
{
  printf("hehehe\n");
}

int main(void)
{
    timer_conf_t timer_conf;
    timer_start(&timer_conf, 5000, 1, timer_thread,NULL);
    sleep(3);
    timer_config(&timer_conf,5000);
    sleep(50);
    timer_stop(&timer_conf);
    return 0;
}
#endif
